<?php

namespace App\Models\Coll;

use App\Models\BasicModel;
use App\Models\User;
use App\Models\Users\MoneyLog;
use Dcat\Admin\Traits\HasDateTimeFormatter;


class CollOrder extends BasicModel
{
	use HasDateTimeFormatter;


    protected $table = 'coll_order';

    public function place($uid,$price){

        $user=User::query()->find($uid);
        if($user->money<$price) throw new \Exception('余额不足');

        if($price!=config('base.burn_price')) throw new \Exception('金额变动请刷新页面重试');

        $coll=CollectionDebri::query()->select(['id','c_id','image'])->where('status',1)->orderByRaw('RAND()')->take(1)->first();
        if(empty($coll)) throw new \Exception('系统碎片不足');

        $coll->status=2;
        $coll->save();

        UserCollection::create(['uid'=>$uid,'c_id'=>$coll->id,'type'=>1]);

        $data=[
            'uid'=>$uid,
            'debris_id'=>$coll->id,
            'price'=>$price,
            'status'=>2
        ];

        $order=self::create($data);

        (new MoneyLog())->add($uid,-$price,'烧香消费',6,$order->id);

        return $coll;


    }
}
